﻿using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using LNSServer.Models;
using LNSServer.VO.Report;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;

namespace LNSServer.Controllers
{
    /// <summary>
    /// 报告
    /// </summary>
    [DynamicApiController]
    public class LnsReportController
    {
        private readonly ILogger<LnsReportController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsReportController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] ReportListVO vo)
        {
            RefAsync<int> total = 0;
            List<ReportModel> reportModels = await db.Queryable<ReportModel>()
                .Where(rm => rm.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(vo.Content), rm => rm.Number.Contains(vo.Content) || rm.PjName.Contains(vo.Content))
                .Mapper(async rm => {
                    rm.RealName = await db.Queryable<User>().Select(u => u.Realname).FirstAsync();
                })
                .WhereIF(vo.UId != 0, rm => rm.UId == vo.UId)
                .OrderBy(rm => rm.BeginTime, OrderByType.Desc)
                .ToPageListAsync(vo.PageIndex, vo.PageSize, total);
            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = reportModels,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] ReportSaveVO vo)
        {
            ReportModel reportModels = await db.Insertable<ReportModel>(vo.Adapt<ReportModel>())
                .ExecuteReturnEntityAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = reportModels,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] ReportDeleteVO vo)
        {
            await db.Updateable<ReportModel>(new ReportModel { Id = vo.Id, IsActive = 0})
                .UpdateColumns(rm => rm.IsActive)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] ReportShowVO vo)
        {
            ReportModel reportModel = await db.Queryable<ReportModel>().InSingleAsync(vo.Id);

            Project project = await db.Queryable<Project>().InSingleAsync(reportModel.PjId);

            MapModel mapModel = await db.Queryable<MapModel>().InSingleAsync(project.MapId);

            Robot robot = await db.Queryable<Robot>().InSingleAsync(project.RbtId);

            TestUseCase testUseCase = await db.Queryable<TestUseCase>().InSingleAsync(project.TUCId);

            UnifyContext.Fill(new { Project = project, Map = mapModel, Robot = robot, TestUseCase = testUseCase });

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = reportModel,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// Unity端根据工程Id获取所有报告
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetReportByPjId([FromBody] ReportGetReportByPjIdVO vo)
        {
            List<ReportModel> reportModels = await db.Queryable<ReportModel>()
                .Where(rm => rm.IsActive == 1)
                .Where(rm => rm.PjId == vo.PjId)
                .ToListAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = reportModels,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
